const { defineConfig } = require("@vue/cli-service");
const { readdirSync } = require("fs");
const { resolve } = require('path');
const webpack = require("webpack");
const { pageConfig, tabNavs, pageNames } = require('./cli/create-nav');
const { ModuleFederationPlugin } = require("@module-federation/enhanced");

process.env.VUE_APP_VERSION = require('./package.json').version;

const env = {
  NODE_ENV: process.env.NODE_ENV
};

for (const key in process.env) {
  if (key.startsWith('VUE_APP_')) {
    // 将环境变量中的 VUE_APP_ 前缀去掉
    env[key.slice(8)] = process.env[key];
  }
}

module.exports = defineConfig({
  transpileDependencies: true,
  lintOnSave: false,
  productionSourceMap: false,
  publicPath: process.env.NODE_ENV == 'development' ? './' : process.env.VUE_APP_PUBLIC_PATH,
  pages: {
    ...pageNames.reduce((prev, cur) => {
      prev[cur] = {
        entry: `src/pages/${cur}/index.js`,
        template: `src/pages/${cur}/index.html`,
        filename: `${cur}.html`,
        title: cur,
        inject: false
      }
      return prev;
    }, {}),
    index: {
      entry: 'src/pages/entry.js',
      filename: `index.html`,
      title: 'index',
      inject: false,
      // templateContent: ({ htmlWebpackPlugin }) => `<script>location.replace('${process.env.NODE_ENV == 'development' ? `./${tabNavs[0]}.html` : process.env.VUE_APP_ENTRY}')</script>`,
    }
  },
  devServer: {
    host: '0.0.0.0',
    headers: {
      "Access-Control-Allow-Origin": "*",
      "Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, PATCH, OPTIONS",
      "Access-Control-Allow-Headers":
        "X-Requested-With, content-type, Authorization",
    }
  },
  configureWebpack: {
    resolve: {
      alias: {
        '@': resolve(__dirname, 'src')
      }
    },
    experiments: {
      topLevelAwait: true
    },
    plugins: [
      new ModuleFederationPlugin({
        name: 'wxy_web',
        remotes: {
          wxy_core: `wxy_core@${env.CORE_FEDERATION_HOST}wxy_core.js`,
          wxy_core: `wxy_core@${env.LOGIC_FEDERATION_HOST}wxy_core.js`,
        },
        shared: {
          vue: { singleton: true, requiredVersion: '^3.5.0', eager: true },
          qs: { singleton: true, requiredVersion: '^6.14.0', eager: true },
        },
        dev: true
      }),
      new webpack.DefinePlugin({
        "process.env.pages": JSON.stringify(pageConfig),
        "process.env.tabNavs": JSON.stringify(tabNavs),
        "process.env.app": JSON.stringify(env)
      })
    ]
  },
  chainWebpack: (config) => {
    for (const name in pageConfig) {
      const page = pageConfig[name];

      config.plugin('html-' + name).tap(args => {
        args[0].pageName = name;
        args[0].pageTitle = page.title;
        return args;
      });
    }

    // config.module.rule('vue').use('vue-loader').tap((options) => ({
    //   ...options,
    //   reactivityTransform: true,
    //   compilerOptions: {
    //     scoped: true
    //   }
    // }));
  }
});
